package com.sky.service.user.impl;

import com.sky.context.BaseContext;
import com.sky.mapper.user.AddressBookMapper;
import com.sky.pojo.AddressBook;
import com.sky.service.user.AddressBookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @Description AddressBookServiceImpl
 * @Author lyh
 * @Date 2024-10-08
 */
@Service
public class AddressBookServiceImpl implements AddressBookService {
    @Autowired
    private AddressBookMapper addressBookMapper;

    /**
     * 获取当前用户所有的地址
     * @return
     */
    @Override
    public List<AddressBook> list() {
        Long userId= BaseContext.getCurrentId();
        List<AddressBook> list=addressBookMapper.getListByUserId(userId);
        return list;
    }

    /**
     * 新增地址
     * @param addressBook
     */
    @Override
    public void addAddress(AddressBook addressBook) {
        //设置当前登录用户id
        addressBook.setUserId(BaseContext.getCurrentId());
        //  设置为非默认地址
        addressBook.setIsDefault(0);
        addressBookMapper.addAddress(addressBook);
    }

    /**
     * 根据id查询地址
     * @param id
     * @return
     */
    @Override
    public AddressBook getById(Long id) {
        return addressBookMapper.getById(id);
    }

    /**
     * 根据id修改地址
     * @param addressBook
     */
    @Override
    public void update(AddressBook addressBook) {
       addressBookMapper.update(addressBook);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void setDefault(AddressBook addressBook) {
        //将当前用户的所有地址设置为普通地址（非默认地址）
      addressBook.setIsDefault(0);
      addressBook.setUserId(BaseContext.getCurrentId());
      addressBookMapper.setDefaultByUserId(addressBook);
      //设置默认地址
      addressBook.setIsDefault(1);
      addressBookMapper.setDefaultById(addressBook);
    }

    @Override
    public void deleteById(Long id) {
        addressBookMapper.deleteById(id);
    }

    @Override
    public List<AddressBook> getDefault() {
        Long userId=BaseContext.getCurrentId();
        return addressBookMapper.getDefault(userId);
    }
}
